﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Util.Exceptions;

namespace IterationLife.Extensions.HttpRequest
{
    /// <summary>
    /// Web操作
    /// </summary>
    public static class Web
    {
        /// <summary>  
        /// Get请求与获取结果  
        /// </summary>  
        public static string HttpGet(string Url, Dictionary<string, string> datas = null, int tryIndex = 1)
        {
            if (tryIndex > 2)
                throw new Warning(tryIndex + "次尝试请求,均失败");
            try
            {
                if (datas != null)
                {
                    var postDataStr = DicToHttpParams(datas);
                    if (Url.IndexOf("?") > 0)
                        Url += ("&" + postDataStr);
                    else
                        Url += ("?" + postDataStr);
                }
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "GET";
                request.ContentType = "application/json";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8);
                StringBuilder result = new StringBuilder();
                while (true)
                {
                    var line = reader.ReadLine();
                    if (line == null)
                        break;
                    result.AppendLine(line);
                }
                //result = myStreamReader.ReadToEnd();
                reader.Close();
                myResponseStream.Close();
                response.Close();
                return result.ToString();
            }
            catch (Exception e)
            {
                return HttpGet(Url, datas, tryIndex + 1);
            }
        }

        /// <summary>  
        /// POST请求与获取结果  
        /// </summary>  
        public static string HttpPost(string Url, Dictionary<string, string> datas = null, Dictionary<string, string> headers = null)
        {
            var postDataStr = datas == null ? "" : DicToHttpParams(datas);
            byte[] byteArray = Encoding.UTF8.GetBytes(postDataStr);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataStr.Length;
            request.Accept = "*/*";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
            if (headers != null)
                foreach (var head in headers)
                    request.Headers[head.Key] = head.Value;
            Stream newStream = request.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8);
            StringBuilder result = new StringBuilder();
            while (true)
            {
                var line = reader.ReadLine();
                if (line == null)
                    break;
                result.AppendLine(line);
            }
            reader.Close();
            myResponseStream.Close();
            response.Close();
            return result.ToString();
        }

        public static string DicToHttpParams(Dictionary<string, string> datas)
        {
            var postDataStr = "";
            foreach (var data in datas)
            {
                postDataStr += string.Format("{0}={1}&", data.Key, UrlEncode(data.Value));
            }
            return postDataStr.TrimEnd('&');
        }

        /// <summary>
        /// 对文本进行Url编码
        /// </summary>
        /// <param name="value">文本</param>
        public static string UrlEncode(string value)
        {
            return WebUtility.UrlEncode(value);
        }

        /// <summary>
        /// 对文本进行Url解码
        /// </summary>
        /// <param name="value">已编码的文本</param>
        public static string UrlDecode(string value)
        {
            return WebUtility.UrlDecode(value);
        }
    }
}
